<template>
  <div>
    <!-- 按钮 -->
    <el-button
      type="primary"
      icon="el-icon-plus"
      style="margin: 10px 0"
      @click="showDialog"
      >添加</el-button
    >
    <!-- 表格组件 -->
    <el-table style="width: 100%" border :data="list">
      <el-table-column type="index" label="序号" width="80px" align="center">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column prop="prop" label="品牌LOGO" width="width">
        <template slot-scope="{ row, $index }">
          <img :src="row.logoUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row, $index }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="updateTradeMark(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteTradeMark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      style="margin-top: 20px; text-align: center"
      @current-change="getPageList"
      @size-change="handleSizeChange"
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-count="7"
      :page-sizes="[3, 5, 10]"
      layout="prev, pager, next, jumper,->,total, sizes"
    >
    </el-pagination>
    <!-- 对话框 -->
    <el-dialog
      :title="tmForm.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogFormVisible"
    >
      <el-form style="width: 80%" :model="tmForm" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过2mb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "tradeMark",
  data() {
    // 自定义校验规则
    const validateTmName = (rule, value, callback) => {
      let length = value.trim().length;
      if (length > 10 || value < 1) {
        return callback(new Error("品牌名称必须是1-10位"));
      }
      callback();
    };

    return {
      // 当前页
      page: 1,
      // 每页展示数据条数
      limit: 3,
      // 总共数据条数
      total: 0,
      // 列表展示的数据
      list: [],
      // 控制对话框显示与隐藏
      dialogFormVisible: false,
      // 上传的图片
      imgUrl: "",
      // 收集品牌信息
      tmForm: {
        tmName: "",
        logoUrl: "",
      },
      // 对话框表单验证规则
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          { validator: validateTmName, trigger: "change" },
        ],
        logoUrl: { required: true, message: "请选择品牌的图片" },
      },
    };
  },
  methods: {
    // 获取列表数据
    async getPageList(page = 1) {
      this.page = page;
      let result = await this.$API.trademark.reqTradeMarkList(page, this.limit);
      if (result.code === 200) {
        this.total = result.data.total;
        this.list = result.data.records;
      }
    },
    // 处理每页数据条数变化
    handleSizeChange(size) {
      this.limit = size;
      this.getPageList();
    },
    // 点击添加品牌按钮显示对话框
    showDialog() {
      // 先清空之前的数据
      this.tmForm = { tmName: "", logoUrl: "" };
      this.dialogFormVisible = true;
    },
    // 点击修改按钮
    updateTradeMark(row) {
      Object.assign(this.tmForm, row);
      this.dialogFormVisible = true;
    },
    // 点击删除按钮
    deleteTradeMark(row) {
      this.$confirm(`您确定要删除${row.tmName}吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            let result = await this.$API.trademark.reqDeleteTradeMark(row.id);
            if (result.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getPageList(
                this.list.length > 1 ? this.page : this.page - 1 || 1
              );
            }
          } catch (e) {
            console.log(e);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      this.tmForm.logoUrl = res.data;
    },
    // 图片上传之前
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    // 点击对话框的确定按钮
    addOrUpdateTradeMark() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          try {
            let result = await this.$API.trademark.reqAddOrUpdateTradeMark(
              this.tmForm
            );
            if ((result.code = 200)) {
              // 弹出信息并再次获取品牌列表
              this.$message.success(
                this.tmForm.id ? "修改品牌成功" : "添加品牌成功"
              );
              this.getPageList(this.page);
            } else {
              this.$message.error(
                this.tmForm.id ? "修改品牌失败" : "添加品牌失败"
              );
              throw result;
            }
          } catch (e) {
            console.log(e);
          }
        } else {
          return false;
        }
      });
    },
  },
  mounted() {
    this.getPageList();
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
